package com.droidzxy.membership;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.auth.AGConnectAuthCredential;
import com.huawei.agconnect.auth.PhoneAuthProvider;
import com.huawei.agconnect.auth.SignInResult;
import com.huawei.agconnect.auth.VerifyCodeResult;
import com.huawei.agconnect.auth.VerifyCodeSettings;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hmf.tasks.TaskExecutors;

import java.util.Locale;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{

    private Button btnLogin;
    private Button btnRegister;
    private Button btnForget;
    private Button btnSend;

    private EditText edtPhone;
    private EditText edtPassword;
    private EditText edtVerify;

    private LinearLayout layoutPassword;
    private LinearLayout layoutVerify;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(getResources().getColor(R.color.statuscolor));
        }


        btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this);

        btnRegister = findViewById(R.id.btn_register);
        btnRegister.setOnClickListener(this);
        btnForget = findViewById(R.id.btn_forget);
        btnForget.setOnClickListener(this);
        btnSend = findViewById(R.id.btn_send);
        btnSend.setOnClickListener(this);

        layoutPassword = findViewById(R.id.layout_password);
        layoutVerify = findViewById(R.id.layout_verify);

        edtPhone = findViewById(R.id.edt_phone);
        edtPassword = findViewById(R.id.edt_password);
        edtVerify = findViewById(R.id.edt_verify);


    }

    @Override
    protected void onStart() {
        super.onStart();
        if (AGConnectAuth.getInstance().getCurrentUser() != null) {
            AGConnectAuth.getInstance().signOut();
        }
    }



    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                if(checkInput()) {
                    login();
                }
                break;
            case R.id.btn_register:
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_forget:
                if(layoutPassword.getVisibility() == View.VISIBLE) {
                    layoutPassword.setVisibility(View.GONE);
                    layoutVerify.setVisibility(View.VISIBLE);

                    btnForget.setText("密码登录>");
                } else {
                    layoutPassword.setVisibility(View.VISIBLE);
                    layoutVerify.setVisibility(View.GONE);

                    btnForget.setText("忘记密码?");
                }
                break;
            case R.id.btn_send:
                if(checkInputForVerify()) {
                    sendVerificationCode();
                    edtVerify.setText("");
                    btnSend.setEnabled(false);
                    btnSend.setBackgroundColor(getColor(android.R.color.darker_gray));
                    new CountDownTimer(30000, 1000) {

                        public void onTick(long millisUntilFinished) {
                            btnSend.setText(String.valueOf(millisUntilFinished / 1000) +" s");

                        }

                        public void onFinish() {
                            btnSend.setBackground(ContextCompat.getDrawable(getBaseContext(), R.drawable.rectangle));
                            btnSend.setEnabled(true);
                            btnSend.setText("获取验证码");
                        }
                    }.start();
                }
                break;
        }
    }


    private void sendVerificationCode() {
        VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
                .action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
                .sendInterval(30) //shortest send interval ，30-120s
                .locale(Locale.SIMPLIFIED_CHINESE) //optional,must contain country and language eg:zh_CN
                .build();

        String countryCode = "86";
        String phoneNumber = edtPhone.getText().toString().trim();
        Task<VerifyCodeResult> task =  AGConnectAuth.getInstance().requestVerifyCode(countryCode, phoneNumber, settings);
        task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
            @Override
            public void onSuccess(VerifyCodeResult verifyCodeResult) {
                Toast.makeText(LoginActivity.this, "请求验证码成功", Toast.LENGTH_SHORT).show();
                //You need to get the verification code from your phone
                btnSend.setEnabled(false);
            }
        }).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Toast.makeText(LoginActivity.this, "requestVerifyCode fail:" + e, Toast.LENGTH_SHORT).show();
                btnSend.setEnabled(true);
            }
        });

    }

    private void login() {
        String countryCode = "86";
        String phoneNumber = edtPhone.getText().toString().trim();
        String password = edtPassword.getText().toString().trim();
        String verifyCode = edtVerify.getText().toString().trim();
        AGConnectAuthCredential credential;
        if (layoutPassword.getVisibility() == View.VISIBLE) {
            credential = PhoneAuthProvider.credentialWithPassword(countryCode, phoneNumber, password);
        } else {
            //If you do not have a password, param password can be null
            credential = PhoneAuthProvider.credentialWithVerifyCode(countryCode, phoneNumber, null, verifyCode);
        }
        signIn(credential);
    }


    private void signIn(AGConnectAuthCredential credential) {
        AGConnectAuth.getInstance().signIn(credential)
                .addOnSuccessListener(new OnSuccessListener<SignInResult>() {
                    @Override
                    public void onSuccess(SignInResult signInResult) {
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
//                        LoginActivity.this.finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {
                        Toast.makeText(LoginActivity.this, "signIn fail:" + e, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private boolean checkInput() {
        boolean formatOK = true;
        String msg = "";
        if(edtPhone.getText().length() != 11) {
            formatOK = false;
            msg = "手机号错误";
        } else if(layoutPassword.getVisibility() == View.VISIBLE) {
            if(edtPassword.getText().length() == 0) {
                formatOK = false;
                msg = "密码不能为空";
            }
        } else if(edtVerify.getText().length() == 0) {
            formatOK = false;
            msg = "验证码不能为空";
        }
        if(formatOK == false) {
            Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
        }
        return formatOK;
    }


    private boolean checkInputForVerify() {
        boolean formatOK = true;
        String msg = "";
        if(edtPhone.getText().length() != 11) {
            formatOK = false;
            msg = "手机号错误";
        }
        return formatOK;
    }


}